﻿using EntityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Super_Star.Controllers
{
    /// <summary>
    /// 食堂表控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class EM_CanteenController : ControllerBase
    {
        private readonly APIDBContext DB;
        public EM_CanteenController(APIDBContext context)
        {
            DB = context;
        }
        /// <summary>
        /// 获取全部数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Result Get()
        {
            Result result = new Result();

            var resulrData = DB.EM_Canteen.ToList<EM_Canteen>();
            result.Data = resulrData;
            result.Code = 200;
            result.Author = "123456@qq.com";
            return result;
        }

        /// <summary>
        /// 根据ID获取数据
        /// ResultFull 风格
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        /// /// Path:路径参数
        [HttpGet("{Id}")]
        public Result Get(Guid Id)
        {
            Result result = new Result();
            // where: 过滤行
            // select: 过滤列
            // tolist(): 筛选一个范围的数据(集合)
            // FirstOrDefault(): 筛选第一条符合条件的数据行(对象)
            // <> : 确认数据类型( 泛型 )

            EM_Canteen? resulrData = DB.EM_Canteen.Where(w => w.Id == Id).FirstOrDefault<EM_Canteen>();
            if (resulrData == null)
            {
                result.Code = 404;
            }
            else
            {
                result.Code = 200;
                result.Data = resulrData;
            }
            return result;
        }

        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="canteen"></param>
        /// <returns></returns>
        [HttpPost]
        public Result AddCanteen([FromBody] EM_Canteen canteen)
        {
            Result result = new Result();
            DB.EM_Canteen.Add(canteen);
            DB.SaveChanges();

            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpDelete]
        public Result DelCanteen(Guid id)
        {
            Result result = new Result();
            EM_Canteen? canteen = DB.EM_Canteen.Where(w => w.Id == id).SingleOrDefault();
            if (canteen != null)
                DB.EM_Canteen.Remove(canteen);
            result.Data = DB.SaveChanges();
            return result;

        }

        /// <summary>
        /// 更改
        /// </summary>
        /// <param name="canteen"></param>
        /// <returns></returns>
        [HttpPut]
        public Result UpCanteen([FromBody] EM_Canteen canteen)
        {
            Result result = new Result();
            DB.EM_Canteen.Update(canteen);
            result.Data = DB.SaveChanges();
            return result;
        }

    }
}
